﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utilities;
using StockImport.http;
using StockImport.dataimport.otc.dailyindex;
using HAP = HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Collections;
using StockCommon;
using StockCommon.sidehelper;


namespace StockImport.dataimport.tse.categoryupdate
{
    public class Tse_CategoryUpdater : HttpContentFetcher
    {

        public override string getTaskName()
        {
            throw new NotImplementedException();
        }
        public override string getVersion()
        {
            throw new NotImplementedException();
        }
        public override bool suitableForDate(DateTime d)
        {
            return true;
        }
        

        protected static List<String> 上市產業分類編號 = null;
        protected List<String> getIndustryTypeIds()
        {
            if (上市產業分類編號 != null)
                return 上市產業分類編號;
            List<String> r = new List<string>();
            String[] rs ={"01","02","03","04","05","06","07","21","22","08","09","10","11","12","13",
                                    "24","25","26","27","28","29","30","31","14","15","16","17","18","23","19","20"};
            foreach (String s in rs)
                r.Add(s);
            上市產業分類編號 = r;
            return 上市產業分類編號;
        }

        protected String getURL(String id,DateTime d)
        {
            String template = "http://www.twse.com.tw/ch/trading/exchange/MI_INDEX/genpage/Report${yyyy}${MM}/A112${yyyy}${MM}${dd}{0}.php?select2={0}&chk_date=${yy}/${MM}/${dd}";
            String r1=replaceYMD(template, d);
            String url=String.Format(r1, id);
            return url;
        }

        Regex titleRegx = new Regex(@"每日收盤行情\([(^\)+)]\)", RegexOptions.IgnoreCase);


        public void processIndustyType(DateTime targetDate)
        {
            targetDate=DateUtils.getValidTradeDate(targetDate);
            List<String> catCodes = getIndustryTypeIds();
            int seq = 0;
            foreach (String catcode in catCodes)
            {
                Hashtable codeNames = new Hashtable();
                String IndustryCatName = ExtraceSecurities(targetDate, catcode, codeNames);
                seq++;
                if (codeNames.Count == 0)
                    continue;
                uppdateIndustyType(IndustryCatName, catcode, codeNames,seq);
                codeNames.Clear();
            }
        }
        private String ExtraceSecurities(DateTime targetDate, String catcode, Hashtable codeNames)
        {
            String url = getURL(catcode, targetDate);
            UpdateResult httpResult = UrlGet.process(url);
            String IndustryTypeName = "";

            if (httpResult.hasContent())
            {
                HAP.HtmlDocument doc = new HAP.HtmlDocument();
                doc.LoadHtml(httpResult.getContent());
                HAP.HtmlNodeCollection ns = doc.DocumentNode.SelectNodes("//th[@class='til_2']");
                if (ns == null)
                    return IndustryTypeName;
                foreach (HAP.HtmlNode n in ns)
                {
                    String t = n.InnerText;
                    int pos = t.IndexOf("每日收盤行情(");
                    if (pos < 0)
                        continue;
                    t=t.Substring(pos+"每日收盤行情(".Length);
                    pos=t.IndexOf(")");
                    t=t.Substring(0, pos);
                    IndustryTypeName = t;

                }
                //處理每一張.
                ns = doc.DocumentNode.SelectNodes("//tr[@class='basic2']");
                if (ns != null)
                {

                    foreach (HAP.HtmlNode n in ns)
                    {
                        if(n.ChildNodes.Count<11)
                            continue;

                        String code = n.ChildNodes[0].InnerText.Trim();
                        String securityName = n.ChildNodes[1].InnerText.Trim();
                        if (code.Contains("證券"))
                            continue;
                        codeNames.Add(code, securityName);
                    }
                }

            }
            return IndustryTypeName;
        }

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        protected void uppdateIndustyType(String catName, String catcode, Hashtable codeNames, int seq)
        {
            Guid catId=StockManager.UpdateTseBasicCategory(catName, catcode, seq);

            //1.更新category = base.
            foreach (String k in codeNames.Keys)
            {
                String name = (String)codeNames[k];
                if (StockManager.updateTseStockCategory(k, catName, catId))
                    continue;
                UnCategoriedStockManager.AddUnCategoriedStock(k, name, "tse", catName, catId);
            }
        }
    }
}
